package com.dlc.felear.xiaoensale.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.dlc.felear.xiaoensale.R;
import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.customView.ConfirmDialog;
import com.dlc.felear.xiaoensale.customView.MultInputDialog;
import com.dlc.felear.xiaoensale.customView.SingleInputDialog;
import com.dlc.felear.xiaoensale.dao.LocalUserDao;
import com.dlc.felear.xiaoensale.dao.MenuTypeDao;
import com.dlc.felear.xiaoensale.dao.OperatorDao;
import com.dlc.felear.xiaoensale.entity.LocalUser;
import com.dlc.felear.xiaoensale.entity.MenuType;
import com.dlc.felear.xiaoensale.entity.Operator;
import com.dlc.felear.xiaoensale.helper.JsonHelper;
import com.dlc.felear.xiaoensale.helper.OkHttpManager;
import com.dlc.felear.xiaoensale.utils.HttpApi;
import com.dlc.felear.xiaoensale.utils.JasyptUtil;
import com.dlc.felear.xiaoensale.utils.TempOperate;
import com.dlc.felear.xiaoensale.utils.UuidUtil;
import com.itdlc.android.library.utils.APPDidUtil;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


public class MenuTypeAdapter extends BaseAdapter implements View.OnClickListener,MultInputDialog.MultiDialogCallback,
        ConfirmDialog.ConfirmDialogCallback, SingleInputDialog.SingleDialogCallback {

    private static final String TAG = "MenuTypeAdapter";
    // 上下文
    private Activity context;
    // 数据
    private List<MenuType> items;
    private int type = 0;
    private int code = 0;
    private ConfirmDialog confirmDialog;
    private String tempId;
    private MenuTypeDao menuTypeDao;
    private OperatorDao operatorDao;
    private SingleInputDialog singleInputDialog;
    private LocalUserDao localUserDao;
    private MultInputDialog multInputDialog;

    public void setValue(int type, int code) {
        this.code = code;
        this.type = type;
    }

    public MenuTypeAdapter(Context context) {
        this.context = (Activity) context;
        items = new ArrayList<>();
        operatorDao = new OperatorDao(context);
        menuTypeDao = new MenuTypeDao(context);
        confirmDialog = new ConfirmDialog(context, this);
        multInputDialog=new MultInputDialog(context,this);
        singleInputDialog = new SingleInputDialog(context, this);
        localUserDao = new LocalUserDao(context);
        initDalg();
    }

    private void initDalg(){
//        multInputDialog.setEtInputType();
//        multInputDialog.setTips("a","n","x");
//        multInputDialog.setHintMsg("输入参数","输入参数","输入参数");
    }

    public List<MenuType> getData() {
        return items;
    }


    public void setItems(List<MenuType> data) {
        if (data.isEmpty()) {
            notifyDataSetChanged();
            return;
        }
        items.clear();
        items.addAll(data);
        notifyDataSetChanged();
    }

    public void clearData() {
        items.clear();
        notifyDataSetChanged();
    }


    @Override
    public int getCount() {
        return items == null ? 0 : items.size();
    }

    @Override
    public MenuType getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = View.inflate(context, R.layout.adapter_menu_type_item, null);
            holder.tv_name = convertView.findViewById(R.id.tv_name);
            holder.tv1 = convertView.findViewById(R.id.tv_1);
            holder.tv2 = convertView.findViewById(R.id.tv_2);
            holder.tv3 = convertView.findViewById(R.id.tv_3);
            holder.tv4 = convertView.findViewById(R.id.tv_4);
            holder.tv1.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            holder.tv2.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            holder.tv3.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            holder.tv4.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        if (type == 1) {
            holder.tv3.setText("选择");
        }
        holder.tv1.setTag(R.id.tv_1, position);
        holder.tv1.setOnClickListener(this);

        holder.tv2.setTag(R.id.tv_2, position);
        holder.tv2.setOnClickListener(this);

        holder.tv3.setTag(R.id.tv_3, position);
        holder.tv3.setOnClickListener(this);

        holder.tv4.setTag(R.id.tv_4, position);
        holder.tv4.setOnClickListener(this);
        holder.tv_name.setText(items.get(position).getName());
        return convertView;
    }

    @Override
    public void onClick(View v) {
        int p = (int) v.getTag(v.getId());
        MenuType menuType = items.get(p);
        tempId = menuType.getId();
        switch (v.getId()) {
            case R.id.tv_1:
                createTemp(menuType.getId(),menuType.getName());
                break;
            case R.id.tv_2:
                if (type == 0) {
                    confirmDialog.showDialog("是否要删除", R.id.tv_2);
                }
                break;
            case R.id.tv_3:
                if (type == 0) {
                    confirmDialog.showDialog("是否要上传分类", R.id.tv_3);
                } else {
                    returnmsg(menuType);
                }
                break;
            case R.id.tv_4:
//                multInputDialog.showDialog(menuType.getId());
//                CcCookingTimeParamer ccCookingTimeParamer =ccCookingTimeDao.queryForId(menuType.getId());
//                if(ccCookingTimeParamer!=null){
//                    multInputDialog.setHintMsg(Float.toString(ccCookingTimeParamer.getA()),
//                            Float.toString(ccCookingTimeParamer.getM()),
//                            Float.toString(ccCookingTimeParamer.getX()));
//                }
                break;
        }
    }

    @Override
    public void selectResult(int value, int id) {
        if (value == 1) {
            singleInputDialog.setEtInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
            singleInputDialog.setHintMsg("请输入管理员密码");
            singleInputDialog.setMiWen();
            singleInputDialog.setTips("密码");
            singleInputDialog.showDialog(id);
        }
    }

    @Override
    public void SingleDialogInputResult(String value, int id) {
        LocalUser localUser = localUserDao.queryForId(UuidUtil.getUuidByName(Constant.USER_NAME));
        if (localUser == null) {
            showToast("用户不存在，请联系管理员添加用户");
            return;
        }
        if (TextUtils.equals(localUser.getPwd(), value)) {
            if (R.id.tv_2 == id) {
                delete();
            } else if (R.id.tv_3 == id) {
                update();
            }
        } else {
            showToast("密码不正确");
        }
    }

    @Override
    public void multDialogInputResult(String value1, String value2, String value3,String value4, String id) {
        Log.e(TAG,"value1="+value1+" value2="+value2+" value3="+value3+" id="+id);
//        CcCookingTimeParamer ccCookingTimeParamer =ccCookingTimeDao.queryForId(id);
//        if(ccCookingTimeParamer==null){
//            ccCookingTimeParamer=new CcCookingTimeParamer();
//            ccCookingTimeParamer.setId(id);
//            ccCookingTimeParamer.setName(menuTypeDao.queryForId(id).getName());
//        }
//        try {
//            if(Float.parseFloat(value1)>0){
//                ccCookingTimeParamer.setA(Float.parseFloat(value1));
//            }
//            if(Float.parseFloat(value2)>0){
//                ccCookingTimeParamer.setM(Float.parseFloat(value2));
//            }
//            if(Float.parseFloat(value3)>0){
//                ccCookingTimeParamer.setX(Float.parseFloat(value3));
//            }
//            ccCookingTimeDao.createOrUpdate(ccCookingTimeParamer);
//            showToast("保存成功");
//        }catch (Exception e){
//            showToast("输入数据格式有误，请查证");
//        }

    }

    static class ViewHolder {
        TextView tv_name, tv1, tv2, tv3,tv4;
    }

    private void delete() {
        menuTypeDao.delete(menuTypeDao.queryForId(tempId));
        operatorDao.deleteByCid(tempId);
        items.clear();
        items.addAll(menuTypeDao.queryForAll());
        notifyDataSetChanged();
        showToast("删除完成");
//        deleteData(tempId);
    }

    private void deleteData(String id) {
        HashMap<String, Object> paramers = new HashMap<>();
        paramers.put("id", id);
        String sign = JasyptUtil.getInstance().getSign(paramers);
        paramers.put("sign", sign);
        OkHttpManager.HttpPostJson(HttpApi.URL_DEL_CAT, paramers, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                Log.e(TAG, "删除菜谱分类数据" + e.getMessage());
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    Log.e(TAG, "删除菜谱分类数据" + s);
                } catch (Exception e) {

                }
            }
        });
    }


    private void createTemp(String id,String name) {
    }

    private void showToast(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    private void update() {
        MenuType menuType = menuTypeDao.queryForId(tempId);
        List<Operator> tempList = operatorDao.queryForAllByMID(tempId);
        if (tempList == null || tempList.isEmpty()) {
            showToast("分类步骤为空，请先添加步骤模板");
            return;
        }
        Log.e(TAG, "paramer" + JsonHelper.toJson(ListToMap(menuType, tempList)));
        String url = HttpApi.URL_ADD_CAT;
        OkHttpManager.HttpPostJson(url, ListToMap(menuType, tempList), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                Log.e(TAG, "Exception:" + e.getMessage());
                showToast(e.getMessage());
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    Log.e(TAG, "respone:" + s);
                    HashMap<String, Object> map = JsonHelper.parserJson(s, HashMap.class);
                    Log.e(TAG, "onResponse:" + JsonHelper.toJson(map));
                    String key = "msg";
                    if (map.containsKey(key)) {
                        showToast((String) map.get(key));
                    }
                } catch (Exception e) {
                    showToast("数据解析异常");
                }
            }
        });

    }

    private Map<String, Object> ListToMap(MenuType menuType, List<Operator> tempList) {
        Map<String, Object> paramer = new HashMap<>();
        List<TempOperate> list = new ArrayList<>();
        Map<String, Object> paramerList = new HashMap<>();
        for (Operator operator : tempList) {
            TempOperate tempOperate = new TempOperate();
            tempOperate.setDelayTime(operator.getDelayTime());
            tempOperate.setNum(operator.getNum());
            tempOperate.setName(operator.getName());
            tempOperate.setValue(operator.getValue());
            tempOperate.setValue1(operator.getValue1());
            tempOperate.setSerial(operator.getSerial());
            tempOperate.setmId(operator.getmId());
            String tempId = (operator.getNum() + operator.getId()) + operator.getName();
            tempOperate.setId(UuidUtil.getUuidByName(tempId));
            list.add(tempOperate);
        }
        paramer.put("deviceId", APPDidUtil.getAppDid());
        paramer.put("name", menuType.getName());
        paramer.put("weight", menuType.getWeight());
        paramer.put("id", menuType.getId());
        paramerList.put("operateSteps", list);
        paramer.put("data", paramerList);
        paramer.put("sign", JasyptUtil.getInstance().getSign(paramer));
        return paramer;
    }

    private void returnmsg(MenuType menuType) {
        Intent intent = new Intent();
        //把返回数据存入Intent
        intent.putExtra(Constant.OPERATOR_VALUE_1, menuType.getName());
        intent.putExtra(Constant.OPERATOR_VALUE_2, menuType.getId());
        //设置返回数据
        context.setResult(code, intent);
        //关闭Activity
        context.finish();
    }
}